<template>
  <!-- 页面模式 -->
  <div v-if="isPageMode" class="page-mode-container">
    <!-- 头部 -->
    <div class="guide-header">
      <h1 class="guide-title">新手指引</h1>
      <p class="guide-subtitle">请完成以下步骤以开始使用智慧养老服务平台</p>
    </div>

    <div class="guide-content">
      <!-- 进度条 -->
      <div class="progress-bar">
        <el-progress
            :percentage="stepProgress"
            :stroke-width="10"
            :color="progressColor"
            :text-inside="true"
            :status="stepStatus"
        />
      </div>

      <!-- 步骤指示器 -->
      <el-steps :active="currentStep" align-center finish-status="success">
        <el-step title="选择身份" />
        <el-step title="功能介绍" />
        <el-step title="实名认证" />
        <el-step title="完成" />
      </el-steps>

      <!-- 步骤内容区域 -->
      <div class="step-content-wrapper">
        <!-- 动态加载步骤组件 -->
        <component
            :is="currentStepComponent"
            v-bind="currentStepProps"
            @prev="prevStep"
            @next="nextStep"
            @complete="completeGuide"
            @update:selected-identity="selectedIdentity = $event"
            @agree="agreedToPrivacy = true"
            @show-privacy="showPrivacyDialog = true"
            @submit-success="handleAuthSuccess"
            @update:authForm="authForm = $event"
            @update:agreedToPrivacy="agreedToPrivacy = $event"
        />
      </div>
    </div>
  </div>

  <!-- 弹窗模式 -->
  <el-dialog
      v-else
      v-model="localVisible"
      title="新手指引"
      width="900px"
      :close-on-click-modal="false"
      :show-close="false"
      :close-on-press-escape="false"
      :before-close="handleClose"
  >
    <!-- 弹窗模式内容 -->
    <div class="modal-content-wrapper"> <!-- 添加新的包裹容器 -->
      <div class="progress-bar">
        <el-progress
            :percentage="modalStepProgress"
            :stroke-width="10"
            :color="progressColor"
            :text-inside="true"
            :status="modalStepStatus"
        />
      </div>

      <el-steps :active="modalCurrentStep" align-center finish-status="success">
        <el-step title="选择身份" />
        <el-step title="功能介绍" />
        <el-step title="实名认证" />
        <el-step title="完成" />
      </el-steps>

      <div class="guide-content">
        <!-- 动态加载弹窗模式步骤组件 -->
        <component
            :is="modalStepComponent"
            v-bind="modalStepProps"
            @prev="prevModalStep"
            @next="nextModalStep"
            @complete="completeGuide"
            @update:selected-identity="selectedIdentity = $event"
            @agree="agreedToPrivacy = true"
            @show-privacy="showPrivacyDialog = true"
            @submit-success="handleAuthSuccess"
            @update:authForm="authForm = $event"
        />
      </div>
    </div>
  </el-dialog>

  <!-- 隐私政策弹窗 -->
  <PrivacyPolicyDialog v-model="showPrivacyDialog" />
</template>

<script setup>
import { ref, computed, defineProps, defineEmits, watch } from 'vue'
import { useRouter } from 'vue-router'
import StepIdentity from '@/views/Guide/components/StepIdentity.vue'
import StepIntroduction from '@/views/Guide/components/StepIntroduction.vue'
import StepVerification from '@/views/Guide/components/StepVerification.vue'
import StepComplete from '@/views/Guide/components/StepComplete.vue'
import PrivacyPolicyDialog from '@/views/Guide/components/PrivacyPolicyDialog.vue'
import { ElMessageBox } from 'element-plus'

const props = defineProps({
  modelValue: Boolean,
  isPageMode: Boolean
})

const emit = defineEmits(['update:modelValue', 'guide-complete'])

const router = useRouter()

// 状态管理
const localVisible = ref(props.modelValue)
const currentStep = ref(1)
const modalCurrentStep = ref(1)
const selectedIdentity = ref(0)
const authForm = ref({ realName: '', idCard: '', idCardUrl: { front: '', back: '' }})
const isVerified = ref(false) // 添加认证状态
const agreedToPrivacy = ref(false)
const showPrivacyDialog = ref(false)

watch(isVerified, (newVal) => {
  console.log('[父组件] isVerified 状态变化:', newVal)
}, { immediate: true })

watch(currentStep, (newStep) => {
  console.log('[父组件] 当前步骤变化:', newStep)
})

watch(modalCurrentStep, (newStep) => {
  console.log('[父组件] 弹窗模式步骤变化:', newStep)
})

import { onMounted, onUnmounted } from 'vue'

onMounted(() => {
  console.log('[父组件] NewUserGuide 已挂载')
})

onUnmounted(() => {
  console.log('[父组件] NewUserGuide 已卸载')
})

const handleAuthSuccess = (data) => {
  console.log('[父组件] 收到 submit-success 事件，数据:', data)
  authForm.value = {
    ...authForm.value,
    realName: data.realName,
    idCard: data.idCard,
    idCardUrl: data.idCardUrl
  }
  isVerified.value = true
  console.log('[父组件] 设置 isVerified 为 true')
}

// 身份证图片数组形式的 computed
const idCardUrls = computed(() => {
  const urls = []
  if (authForm.value.idCardUrl.front) urls.push(authForm.value.idCardUrl.front)
  if (authForm.value.idCardUrl.back) urls.push(authForm.value.idCardUrl.back)
  return urls
})

// 身份文本描述
const identityText = computed(() => {
  switch (selectedIdentity.value) {
    case 1: return '老人'
    case 2: return '家属'
    case 3: return '志愿者'
    default: return ''
  }
})

// 身份功能特性
const identityFeatures = computed(() => {
  switch (selectedIdentity.value) {
    case 1: return ['健康监测数据查看', '紧急呼叫服务', '服务预约管理', '活动参与记录']
    case 2: return ['老人健康数据查看', '服务预约与管理', '紧急情况通知', '账单支付管理']
    case 3: return ['服务活动报名', '服务记录查看', '社区通知接收', '服务时长统计']
    default: return []
  }
})

// 图片和轮播配置
const identityImages = computed(() => {
  switch (selectedIdentity.value) {
    case 1: return ['/images/elderly1.jpg', '/images/elderly2.jpg']
    case 2: return ['/images/family1.jpg', '/images/family2.jpg']
    case 3: return ['/images/volunteer1.jpg', '/images/volunteer2.jpg']
    default: return []
  }
})

const carouselTitles = computed(() => {
  switch (selectedIdentity.value) {
    case 1: return ['健康监测', '紧急呼叫']
    case 2: return ['健康数据查看', '服务预约']
    case 3: return ['志愿活动', '服务记录']
    default: return []
  }
})

const carouselCaptions = computed(() => {
  switch (selectedIdentity.value) {
    case 1: return ['实时监测您的健康状况', '一键呼叫紧急联系人']
    case 2: return ['查看老人健康报告', '在线预约服务']
    case 3: return ['参加社区志愿服务', '查看服务历史']
    default: return []
  }
})

// 动态组件计算
const currentStepComponent = computed(() => {
  return [
    null,
    StepIdentity,
    StepIntroduction,
    StepVerification,
    StepComplete
  ][currentStep.value]
})

const currentStepProps = computed(() => {
  const commonProps = {
    identityText: identityText.value,
    identityFeatures: identityFeatures.value,
    selectedIdentity: selectedIdentity.value,
    isVerified: isVerified.value // 传递给子组件
  }

  switch (currentStep.value) {
    case 1: return { ...commonProps }
    case 2: return {
      ...commonProps,
      identityImages: identityImages.value,
      carouselTitles: carouselTitles.value,
      carouselCaptions: carouselCaptions.value
    }
    case 3: return {
      ...commonProps,
      authForm: authForm.value
    }
    case 4: return {
      ...commonProps,
      agreedToPrivacy: agreedToPrivacy.value // 统一属性名
    }
    default: return {}
  }
})

const modalStepComponent = computed(() => {
  return [
    null,
    StepIdentity,
    StepIntroduction,
    StepVerification,
    StepComplete
  ][modalCurrentStep.value]
})

const modalStepProps = computed(() => {
  const commonProps = {
    identityText: identityText.value,
    identityFeatures: identityFeatures.value,
    selectedIdentity: selectedIdentity.value,
    isVerified: isVerified.value // 传递给子组件
  }

  switch (modalCurrentStep.value) {
    case 1: return { ...commonProps }
    case 2: return {
      ...commonProps,
      identityImages: identityImages.value,
      carouselTitles: carouselTitles.value,
      carouselCaptions: carouselCaptions.value
    }
    case 3: return {
      ...commonProps,
      authForm: authForm.value
    }
    case 4: return {
      ...commonProps,
      agreedToPrivacy: agreedToPrivacy.value,
      // 添加双向绑定支持
      'onUpdate:agreedToPrivacy': (val) => agreedToPrivacy.value = val
    }
    default: return {}
  }
})

// 进度计算
const stepProgress = computed(() => currentStep.value * 25)
const stepStatus = computed(() => currentStep.value === 4 ? 'success' : undefined)

const modalStepProgress = computed(() => modalCurrentStep.value * 25)
const modalStepStatus = computed(() => modalCurrentStep.value === 4 ? 'success' : undefined)

// 步骤导航
function nextStep(data = {}) {
  if (currentStep.value === 1 && !selectedIdentity.value) {
    alert('请选择您的身份')
    return
  }

  if (data.verified && data.realName && data.idCard && data.idCardUrl) {
    authForm.value = {
      realName: data.realName,
      idCard: data.idCard,
      idCardUrl: data.idCardUrl
    }
  }

  if (currentStep.value < 4) {
    currentStep.value++
  } else {
    completeGuide()
  }
}


function prevStep() {
  if (currentStep.value > 1) currentStep.value--
}

function nextModalStep() {
  if (modalCurrentStep.value === 1 && !selectedIdentity.value) {
    alert('请选择您的身份')
    return
  }

  if (modalCurrentStep.value < 4) {
    modalCurrentStep.value++
  } else {
    completeGuide()
  }
}

function prevModalStep() {
  if (modalCurrentStep.value > 1) modalCurrentStep.value--
}

async function completeGuide() {
  try {

    // 获取用户ID并确保是 Long 类型
    const userData = JSON.parse(localStorage.getItem('user') || '{}');
    const userId = parseInt(userData.userId, 10);
    if (!userId) {
      alert("用户未登录");
      return;
    }

    // 获取 token 并验证
    const token = localStorage.getItem('token');
    if (!token) {
      alert("请先登录");
      return;
    }
    // 使用 computed 属性
    const idCardUrl = idCardUrls.value; // ✅ 使用 computed 值

    // 构建符合 UserSaveParam 格式的完整对象
    const userSaveParam = {
      userId: userId,
      userType: selectedIdentity.value,
      realName: authForm.value.realName || null,
      idCard: authForm.value.idCard || null,
      idCardUrl: idCardUrl.length > 0 ? idCardUrl : null, // ✅ 使用 computed 数据
    };

    console.log("提交数据：", userSaveParam);

    const response = await fetch(`${BASE_URL}/api/v1/users/updateIdentify`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${token}`
      },
      body: JSON.stringify(userSaveParam)
    });

    if (!response.ok) throw new Error("更新用户信息失败");

    const result = await response.json();
    if (result.code !== 2000) throw new Error(result.msg || "更新失败");

    // 更新本地存储的用户信息
    userData.userType = selectedIdentity.value;
    userData.realName = authForm.value.realName;
    userData.idCard = authForm.value.idCard;
    localStorage.setItem('user', JSON.stringify(userData));

    // 触发完成事件
    emit('guide-complete');
    localVisible.value = false;

    // 跳转首页
    router.push('/index');

  } catch (error) {
    console.error("更新用户信息失败", error);
    alert("更新失败，请稍后重试");
  }
}

// 处理弹窗关闭
function handleClose(done) {
  if (modalCurrentStep.value < 4) {
    // 使用Element UI的确认框替代alert
    ElMessageBox.confirm(
        '请完成新手指引流程后才能继续使用',
        '提示',
        {
          confirmButtonText: '继续',
          cancelButtonText: '退出登录',
          type: 'warning',
          showCancelButton: true
        }
    ).then(() => {
      // 用户点击继续，不做任何操作
    }).catch(() => {
      // 用户选择退出登录
      localStorage.removeItem('user');
      localStorage.removeItem('token');
      router.push('/');
      done();
    });
  } else {
    // 已完成流程，允许关闭
    done();
  }
}

// 同步 visible 状态
watch(() => props.modelValue, newVal => localVisible.value = newVal)
watch(() => localVisible.value, newVal => emit('update:modelValue', newVal))

// 定义 BASE_URL
const BASE_URL = window.BASE_URL || 'http://localhost:8080';
</script>

<style scoped>
/* 优化样式 */
.page-mode-container {
  max-width: 1000px;
  margin: 2rem auto;
  padding: 2rem;
  background: white;
  border-radius: 12px;
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.08);
}

.guide-header {
  text-align: center;
  margin-bottom: 2rem;
}

.guide-title {
  font-size: 2rem;
  color: #333;
  margin-bottom: 0.5rem;
}

.guide-subtitle {
  font-size: 1rem;
  color: #666;
}

.progress-bar {
  margin-bottom: 1.5rem;
}

.step-content-wrapper {
  min-height: 500px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 2rem;
  margin-top: 1.5rem;
  background: #f9fafc;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .page-mode-container {
    padding: 1rem;
    margin: 1rem;
  }

  .step-content-wrapper {
    padding: 1rem;
  }
}
/* 弹窗模式专属样式 */
:deep(.el-dialog) {
  border-radius: 12px;
  overflow: hidden;
}

:deep(.el-dialog__header) {
  background: #FFB74D;
  padding: 20px;
  margin: 0;
}

:deep(.el-dialog__title) {
  color: white;
  font-size: 1.5rem;
  font-weight: bold;
}

.modal-content-wrapper {
  padding: 20px 30px;
  max-height: 80vh;
  overflow-y: auto;
}

.guide-content {
  padding: 20px 0;
}

/* 步骤内容区域 */
.step-content-wrapper {
  min-height: 450px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 25px;
  margin-top: 1.5rem;
  background: #f9fafc;
}

/* 响应式调整 */
@media (max-width: 992px) {
  :deep(.el-dialog) {
    width: 90% !important;
    max-width: 700px;
  }

  .step-content-wrapper {
    padding: 15px;
  }
}

@media (max-width: 768px) {
  .page-mode-container {
    padding: 1rem;
    margin: 1rem;
  }

  .step-content-wrapper {
    padding: 1rem;
  }

  :deep(.el-dialog) {
    width: 95% !important;
  }

  :deep(.el-steps) {
    flex-wrap: wrap;
  }

  :deep(.el-step) {
    min-width: 25%;
    margin-bottom: 10px;
  }
}
</style>